package com.demohomework.homeworkdemo.controller;


import com.demohomework.homeworkdemo.pojo.Admin;
import com.demohomework.homeworkdemo.pojo.Assignment;
import com.demohomework.homeworkdemo.pojo.Result;
import com.demohomework.homeworkdemo.pojo.Student;
import com.demohomework.homeworkdemo.service.StudentService;
import com.demohomework.homeworkdemo.util.JwtUtil;
import com.demohomework.homeworkdemo.util.Md5Util;
import com.demohomework.homeworkdemo.util.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Validated
@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;
    //添加学生
    @PostMapping("/add")
public Result add(@RequestBody @Validated Student student) {
    // 检查用户名是否已存在
    Student existingStudent = studentService.findbyUsername(student.getUsername());
        // 检查用户名是否为空
        if (student.getUsername() == null || student.getUsername().trim().isEmpty()) {
            return Result.error("请补全信息"); // 返回失败结果
        }
    if (existingStudent != null) {
        return Result.error("用户名已存在，无法添加"); // 用户名已存在，返回失败
    }

    // 添加学生
    studentService.add(student);
    return Result.success();
}

    //注册
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "\\S{2,15}$") String username,@Pattern(regexp = "\\S{5,10}$") String password) {
        //查询用户
        Student u = studentService.findbyUsername(username);
        if (u==null){
            //注册用户
            studentService.register(username, password);
            return Result.success();
        }else{
            //用户已存在
            return Result.error("用户名已存在");
        }
    }
    //根据id查询作业
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") Integer id) {
        Student s = studentService.findId(id);
        return Result.success(s);
    }

    //登录
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "\\S{2,10}$") String username, @Pattern(regexp = "\\S{5,10}$") String password) {
        //查询用户
        Student loginUser = studentService.findbyUsername(username);
        if (loginUser!=null){
            //验证密码
            if (Md5Util.string2MD5(password).equals(loginUser.getPassword())){
                //登录成功
                Map<String, Object> claims =new HashMap<>();
                claims.put("id",loginUser.getId());
                claims.put("username",loginUser.getUsername());
                //生成jwt token令牌
                String token = JwtUtil.genToken(claims);
                return Result.success(token);
            }else{
                //密码错误
                return Result.error("密码错误");
            }
        }else{
            //用户不存在
            return Result.error("用户不存在");
        }
    }

    //用户信息
    @GetMapping("/studentInfo")
    public Result<Student> studentInfo() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");

        Student student = studentService.findbyUsername(username);
        return Result.success(student);
    }
    //所有学生信息
    @GetMapping
    public Result<List<Student>> list() {
        List<Student> students = studentService.list();
        return Result.success(students);
    }

    //更新用户信息
    @PutMapping("/update")
    public Result update(@RequestBody @Validated Student student ) {
        studentService.update(student);
        return Result.success();
    }

    //修改密码
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params){
        //校验参数
        String oldPwd = (String) params.get("oldPwd");
        String newPwd = (String) params.get("newPwd");
        String rePwd = (String) params.get("rePwd");

        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }

        //原密码验证
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        Student loginStudent = studentService.findbyUsername(username);
        if (!Md5Util.string2MD5(oldPwd).equals(loginStudent.getPassword())){
            return Result.error("原密码错误");
        }
        //新密码验证
        if (!newPwd.equals(rePwd)){
            return Result.error("两次密码不一致");
        }
        //修改密码
        studentService.updatePwd(newPwd);
        return Result.success();
    }
    //删除学生
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        studentService.delete(id);
        return Result.success();
    }
}
